//https://leetcode.cn/problems/evaluate-reverse-polish-notation/
package codeRandomThoughts.Test150逆波兰表达式求值;

import java.util.Stack;

public class Solution {
    /**
     * 逆波兰表达式是一种后缀表达式,即运算符写在后面
     * 遇到数字则入栈
     * 遇到算符则取出栈顶两个数字进行计算
     * 并且将结果压入栈中
     *
     * @param tokens
     * @return
     */
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        int a = 0;
        int b = 0;
        for (int i = 0; i < tokens.length; i++) {
            switch (tokens[i]) {
                case "+": {
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(a + b);
                    break;
                }
                case "-": {
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(b - a);
                    break;
                }
                case "*": {
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(a * b);
                    break;
                }
                case "/": {
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(b / a);
                    break;
                }
                default: {
                    stack.push(Integer.valueOf(tokens[i]));
                    break;
                }
            }
        }
        return stack.pop();
    }

    /**
     * 对上面的代码进行简化
     *
     * @param tokens
     * @return
     */
    public int evalRPN2(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            switch (tokens[i]) {
                case "+": {
                    stack.push(stack.pop() + stack.pop());
                    break;
                }
                case "-": {
                    stack.push(-(stack.pop() - stack.pop()));
                    break;
                }
                case "*": {
                    stack.push(stack.pop() * stack.pop());
                    break;
                }
                case "/": {
                    int k = stack.pop();
                    stack.push(stack.pop() / k);
                    break;
                }
                default: {
                    stack.push(Integer.valueOf(tokens[i]));
                    break;
                }
            }
        }
        return stack.pop();
    }
}
